package cn.passlink.www.Controller;

import cn.passlink.www.Utils.JsonUtils;
import cn.passlink.www.Utils.imgUpload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileUploadController {

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    //上传文件，需要验证
    @PostMapping("/upload")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest httpRequest) {

        try {
            //        检测是否为空
            if (file.isEmpty()) {
                log.error("文件为空");
                return JsonUtils.resultJson(403, "请选择要上传的文件");
            }

            //        检测大小必须小于10mb
            if (file.getSize() >= 10485760 || file.isEmpty()) {
                log.error("文件大小要求小于10MB");
                return JsonUtils.resultJson(403, "文件大小要求小于10MB");
            }

            //返回结果判断
            String fileStr = imgUpload.inputUploadFile(file, uploadFolder);
            //        不是图片
            if (fileStr.equals("NOT_IMAGE")) {
                log.error("NOT_IMAGE");
                return JsonUtils.resultJson(403, "请上传图片！！！");
            }
            //域名获取

            String domain = imgUpload.domain(httpRequest);
            if (domain.equals("UPLOAD_ERROR") || domain.equals("NOT_IMAGE")) {
                log.error("上传失败");
                return JsonUtils.resultJson(403, "上传失败！！！");
            }
            String imgUrl = domain + staticAccessPath + fileStr;
            return JsonUtils.dataJson(200, imgUrl, "图片上传成功");
        } catch (Exception e) {
            log.error("上传失败",e);
            return JsonUtils.resultJson(500, "上传失败!!!");

        }


    }


}
